import 'package:flutter/material.dart';
import 'package:flutter_chat/common/api/apis.dart';
import 'package:flutter_chat/common/constant/constants.dart';
import 'package:flutter_chat/common/entity/entitys.dart';
import 'package:flutter_chat/common/store/stores.dart';
import 'package:flutter_chat/common/utils/loading.dart';
import 'package:flutter_chat/common/utils/toast.dart';
import 'package:flutter_chat/common/widget/widgets.dart';
import 'package:get/get.dart';

import 'state.dart';

class RegisterLogic extends CustomGetxController {
  final RegisterState state = RegisterState();

  final formKey = GlobalKey<FormState>();
  final UserStore userStore = UserStore.to;

  /// 更新登录数据
  updateLoginData(String field, String value) {
    state.registerData = UserRegister(
      username: field == "username" ? value : state.registerData.username,
      password: field == "password" ? value : state.registerData.password,
      confirmPassword: field == "confirmPassword"
          ? value
          : state.registerData.confirmPassword,
    );
  }

  /// 注册
  onRegister() async {
    if (!formKey.currentState!.validate()) {
      return;
    }
    String username = state.registerData.username!;
    String password = state.registerData.password!;
    LoadingUtil.loading(text: "注册中...");
    ResponseEntity res = await UserApi.register(
      username: username,
      password: password,
    );
    LoadingUtil.close();
    if (res.code == 0) {
      ToastUtil.successNotification(
        subTitle: "注册成功",
        duration: const Duration(seconds: 2),
        onClose: () async {
          // 注册成功后自动登录
          LoadingUtil.loading(text: "自动登录中...");
          bool isLogin =
              await UserStore.to.login(username: username, password: password);
          LoadingUtil.close();
          if (isLogin) {
            Get.offAllNamed(RouterName.index);
          }
        },
      );
    } else {
      ToastUtil.errorNotification(subTitle: res.msg);
    }
    // Get.offAllNamed(RouterName.login);
  }
}
